package core.plugins;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class SpencerIDProduct implements IProductIDPlugin 
{
	/**
	 * The next Plugin in the Chain of responsibility
	 */
	IProductIDPlugin nextPlugin;
	
	/**
	 * Default Constructor
	 */
	SpencerIDProduct()
	{
		nextPlugin = null;
	}
	
	@Override
	public String idProduct(String barcode) 
	{
		String productDescription = identifyProduct(barcode);
		
		if (productDescription != null)
		{
			return productDescription;
		}
		else
		{
			//get next productID in chain
			IProductIDPlugin next = getNextPlugin();
			if (next != null)
			{
				return next.idProduct(barcode);
			}
			else
			{
				return null;
			}
		}
	}

	@Override
	public void setNextPlugin(IProductIDPlugin nextPlugin) 
	{
		this.nextPlugin = nextPlugin;
	}

	@Override
	public IProductIDPlugin getNextPlugin() 
	{
		return nextPlugin;
	}

	/**
	 * This method actually takes the barcode and checks the specified
	 * database for the product.  If it finds the product it returns a
	 * String containing the description of the product. Otherwise this
	 * method will return null. 
	 * 
	 * @param barcode The barcode of the product to search for
	 * @return String containing the product Descritption.  If the 
	 * 		product is not found, or there is an error then null is
	 * 		returned.
	 */
	private String identifyProduct(String barcode)
	{
		String dbURL = "https://www.googleapis.com/shopping/search/v1/public/products";
		String charset = "UTF-8";
		String key = "AIzaSyDIEjGjnfuMbU5UUy-QmroncKrql8fXXAI";
		
		try 
		{
			String query = String.format("country=US&q=%s&restrictBy=gtin=%s&key=%s", 
					URLEncoder.encode(barcode,charset), URLEncoder.encode(barcode,charset), 
					URLEncoder.encode(key, charset));
			
			//System.out.println(query);
			//make the connection
			URLConnection connection = new URL(dbURL + "?" + query).openConnection();
			connection.setRequestProperty("Accept-Charset", charset);
			InputStream response = connection.getInputStream();
			
			String responseString = "";
			int currChar;
			
			do
			{
				currChar = response.read();
				if (currChar > -1)
				{
					responseString += (char)currChar;
					//System.out.print((char)currChar);
				}
			} while (currChar >= 0);
			
			//System.out.println(response);
			//System.out.println(responseString);
			
			response.close();
			
			//find the title of this product
			int beginningOf = responseString.indexOf("\"title\":");
			
			if (beginningOf == -1) return null;
			
			int endOf = 0;
			boolean foundBeginning = false;
			
			String prodDescription = "";
			
			for (int i = beginningOf + 8; i < responseString.length(); i++)
			{
				if ((responseString.charAt(i) == '\\') && (responseString.charAt(i+1) == '"'))
				{
					prodDescription += "\"";
					i += 2;
				}
				else if (responseString.charAt(i) == '"') 
				{	
					if (foundBeginning)
					{
						endOf = i;
						break;
					}
					else
					{
						foundBeginning = true;
						beginningOf = i;
					}
				}
				else
				{
					prodDescription += responseString.charAt(i);
				}
			}
			
			//return the substring
			//System.out.println(prodDescription);
			
			return prodDescription;
		} 
		catch (Exception e) 
		{
		} 
		
		return null;
	}
}
